import React, {useState} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
  ActivityIndicator,
  ScrollView,
} from 'react-native';
import {launchCamera, launchImageLibrary, Asset} from 'react-native-image-picker';
import Video from 'react-native-video';
import Ionicons from 'react-native-vector-icons/Ionicons';

// 定义视频类型接口
interface VideoFile {
  uri: string;
  type: string;
  name: string;
  size: number;
  duration?: number;
}

type SelectedVideoType = VideoFile | null;

const VideoUploadScreen = () => {
  const [selectedVideo, setSelectedVideo] = useState<SelectedVideoType>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);

  // 配置选项
const getMediaOptions = (isCamera = false) => {
  const baseOptions = {
    mediaType: 'video' as const,
    quality: 'high' as const, // 改为字符串
    includeBase64: false,
    maxWidth: 1920,
    maxHeight: 1080,
  };

  if (isCamera) {
    return {
      baseOptions,
      cameraType: 'back' as const,
      saveToPhotos: true,
    };
  }

  return baseOptions;
};

  // 选择视频 - 修复类型问题
  const selectVideo = () => {
    launchImageLibrary(getMediaOptions(false) as any, (response) => {
      if (response.didCancel) {
        console.log('用户取消了选择');
      } else if (response.errorCode) {
        Alert.alert('错误', `选择视频失败: ${response.errorMessage}`);
      } else if (response.assets && response.assets.length > 0) {
        const video: Asset = response.assets[0];
        
        // 确保 uri 存在
        if (video.uri) {
          const videoFile: VideoFile = {
            uri: video.uri,
            type: video.type || 'video/mp4',
            name: video.fileName || `video_${Date.now()}.mp4`,
            size: video.fileSize || 0,
            duration: video.duration,
          };
          setSelectedVideo(videoFile);
        } else {
          Alert.alert('错误', '无法获取视频文件');
        }
      }
    });
  };

  // 录制视频 - 修复类型问题
  const recordVideo = () => {
    launchCamera(getMediaOptions(true) as any, (response) => {
      if (response.didCancel) {
        console.log('用户取消了录制');
      } else if (response.errorCode) {
        Alert.alert('错误', `录制视频失败: ${response.errorMessage}`);
      } else if (response.assets && response.assets.length > 0) {
        const video: Asset = response.assets[0];
        
        // 确保 uri 存在
        if (video.uri) {
          const videoFile: VideoFile = {
            uri: video.uri,
            type: video.type || 'video/mp4',
            name: video.fileName || `video_${Date.now()}.mp4`,
            size: video.fileSize || 0,
            duration: video.duration,
          };
          setSelectedVideo(videoFile);
        } else {
          Alert.alert('错误', '无法获取录制的视频');
        }
      }
    });
  };

  // 模拟上传视频
  const uploadVideo = async () => {
    if (!selectedVideo) {
      Alert.alert('提示', '请先选择视频');
      return;
    }

    setUploading(true);
    setUploadProgress(0);

    // 模拟上传进度
    const progressInterval = setInterval(() => {
      setUploadProgress(prev => {
        if (prev >= 100) {
          clearInterval(progressInterval);
          return 100;
        }
        return prev + 10;
      });
    }, 200);

    try {
      // 这里替换为真实的上传API
      // const formData = new FormData();
      // formData.append('video', selectedVideo);
      
      // const response = await fetch('YOUR_UPLOAD_URL', {
      //   method: 'POST',
      //   body: formData,
      //   headers: {
      //     'Content-Type': 'multipart/form-data',
      //   },
      // });

      // 模拟网络请求
      await new Promise<void>(resolve => setTimeout(resolve, 2000));
      
      clearInterval(progressInterval);
      setUploadProgress(100);
      
      Alert.alert('成功', '视频上传成功！');
      setSelectedVideo(null);
    } catch (error) {
      clearInterval(progressInterval);
      Alert.alert('错误', '视频上传失败，请重试');
    } finally {
      setUploading(false);
    }
  };

  // 清除选择的视频
  const clearVideo = () => {
    setSelectedVideo(null);
    setUploadProgress(0);
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>视频上传</Text>
        <Text style={styles.subtitle}>选择或录制视频进行上传</Text>
      </View>

      {/* 视频预览区域 */}
      <View style={styles.previewContainer}>
        {selectedVideo ? (
          <View style={styles.videoWrapper}>
            <Video
              source={{uri: selectedVideo.uri}}
              style={styles.video}
              paused={true}
              resizeMode="cover"
            />
            <TouchableOpacity 
              style={styles.clearButton}
              onPress={clearVideo}
            >
              <Ionicons name="close-circle" size={24} color="#fff" />
            </TouchableOpacity>
            <View style={styles.videoInfo}>
              <Text style={styles.videoName}>
                {selectedVideo.name}
              </Text>
              <Text style={styles.videoSize}>
                {(selectedVideo.size / (1024 * 1024)).toFixed(2)} MB
              </Text>
            </View>
          </View>
        ) : (
          <View style={styles.placeholder}>
            <Ionicons name="videocam-outline" size={80} color="#ccc" />
            <Text style={styles.placeholderText}>
              尚未选择视频
            </Text>
          </View>
        )}
      </View>

      {/* 上传进度 */}
      {uploading && (
        <View style={styles.progressContainer}>
          <View style={styles.progressHeader}>
            <Text style={styles.progressText}>上传中...</Text>
            <Text style={styles.progressPercent}>{uploadProgress}%</Text>
          </View>
          <View style={styles.progressBar}>
            <View 
              style={[
                styles.progressFill, 
                {width: `${uploadProgress}%`}
              ]} 
            />
          </View>
        </View>
      )}

      {/* 操作按钮 */}
      <View style={styles.actionsContainer}>
        <TouchableOpacity 
          style={[styles.button, styles.selectButton]}
          onPress={selectVideo}
          disabled={uploading}
        >
          <Ionicons name="folder-open" size={20} color="#fff" />
          <Text style={styles.buttonText}>选择视频</Text>
        </TouchableOpacity>

        <TouchableOpacity 
          style={[styles.button, styles.recordButton]}
          onPress={recordVideo}
          disabled={uploading}
        >
          <Ionicons name="camera" size={20} color="#fff" />
          <Text style={styles.buttonText}>录制视频</Text>
        </TouchableOpacity>

        <TouchableOpacity 
          style={[
            styles.button, 
            styles.uploadButton,
            (!selectedVideo || uploading) && styles.disabledButton
          ]}
          onPress={uploadVideo}
          disabled={!selectedVideo || uploading}
        >
          {uploading ? (
            <ActivityIndicator size="small" color="#fff" />
          ) : (
            <Ionicons name="cloud-upload" size={20} color="#fff" />
          )}
          <Text style={styles.buttonText}>
            {uploading ? '上传中...' : '上传视频'}
          </Text>
        </TouchableOpacity>
      </View>

      {/* 使用说明 */}
      <View style={styles.instructions}>
        <Text style={styles.instructionsTitle}>使用说明：</Text>
        <Text style={styles.instructionItem}>
          • 支持 MP4、MOV 等常见视频格式
        </Text>
        <Text style={styles.instructionItem}>
          • 视频大小不超过 500MB
        </Text>
        <Text style={styles.instructionItem}>
          • 视频时长不超过 5 分钟
        </Text>
        <Text style={styles.instructionItem}>
          • 确保网络连接稳定
        </Text>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    padding: 20,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 5,
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
  },
  previewContainer: {
    margin: 20,
    backgroundColor: '#fff',
    borderRadius: 12,
    overflow: 'hidden',
    minHeight: 200,
  },
  videoWrapper: {
    position: 'relative',
  },
  video: {
    width: '100%',
    height: 200,
  },
  clearButton: {
    position: 'absolute',
    top: 10,
    right: 10,
    backgroundColor: 'rgba(0,0,0,0.5)',
    borderRadius: 12,
    padding: 4,
  },
  videoInfo: {
    padding: 15,
    backgroundColor: '#f8f8f8',
  },
  videoName: {
    fontSize: 14,
    fontWeight: '500',
    color: '#333',
    marginBottom: 4,
  },
  videoSize: {
    fontSize: 12,
    color: '#666',
  },
  placeholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 40,
  },
  placeholderText: {
    marginTop: 10,
    fontSize: 16,
    color: '#999',
    textAlign: 'center',
  },
  progressContainer: {
    margin: 20,
    backgroundColor: '#fff',
    padding: 15,
    borderRadius: 8,
  },
  progressHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 10,
  },
  progressText: {
    fontSize: 14,
    color: '#333',
  },
  progressPercent: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#007AFF',
  },
  progressBar: {
    height: 6,
    backgroundColor: '#e0e0e0',
    borderRadius: 3,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: '#007AFF',
    borderRadius: 3,
  },
  actionsContainer: {
    padding: 20,
    gap: 12,
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 15,
    borderRadius: 8,
    gap: 8,
  },
  selectButton: {
    backgroundColor: '#34C759',
  },
  recordButton: {
    backgroundColor: '#5856D6',
  },
  uploadButton: {
    backgroundColor: '#007AFF',
  },
  disabledButton: {
    backgroundColor: '#ccc',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  instructions: {
    margin: 20,
    padding: 15,
    backgroundColor: '#fff',
    borderRadius: 8,
  },
  instructionsTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 10,
  },
  instructionItem: {
    fontSize: 14,
    color: '#666',
    marginBottom: 5,
    lineHeight: 20,
  },
});

export default VideoUploadScreen;